<template>
	<view>
		<!-- #ifdef APP-PLUS||H5 -->
		
		<titlebara mode="发文章" :backToIndex="false" :back="true" text="发问答" backgroundColor='#f5f5f5'>
			<view slot="title">
				<image class="showMore" mode='aspectFit' src="https://dnsverify.pfmoto.com/appstatic/community/more.png" @click="showMore">

					<view v-if="content==''||title == ''|| checkboxValue.length==0"
						class="showMore titleCommentTouched_" @click="commentTouched">
						+发布
					</view>
					<view v-else class="showMore titleCommentTouched" @click="commentTouched">+发布</view>
					<view class="titleText">发问答</view>
			</view>
		</titlebara>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<titlebara mode="发文章" :backToIndex="false" :back="true" text="发问答" backgroundColor='#f5f5f5'>
			<view slot="title">
				<view class="titleText">发问答</view>
			</view>
		</titlebara>
		<!-- #endif -->

		<view class="releaseState" :style="{'top':top+'px','height':'calc(100vh - '+top+'px)'}">
			<view class="content-pd">

				<view>

					<u--textarea border="bottom" :confirmType = "done" :show-img-toolbar="true" style="margin-top: 20px;" :autoHeight="true"
						v-model="title" maxlength="60" placeholder="请输入问题标题">
					</u--textarea>
					<view class="question_type">问题类型</view>
					<u-checkbox-group v-model="checkboxValue" size="16" placement="row" @change="checkboxChange">
						<u-checkbox :customStyle="{marginBottom: '30rpx'}" activeColor="#EA5404"
							v-for="(item, index) in checkboxList" :key="index" :label="item.name"
							:name="item.dictionaryId">
						</u-checkbox>
					</u-checkbox-group>
					<editor id="editor" class="ql-container" placeholder="点击输入问题内容" @input="changeData"
						@ready="onEditorReady"></editor>

				</view>
			</view>
			<view class="imageList" v-for="(item, index) in fileList" :key="item.uuid">

				<UploadView v-show="false" :ref="'uploadView'+index" :sourceFileList="fileList" :item="item"
					@uploading="uploading" @delete="uploadDelete" @error="uploadError" @success="uploadSuccess"
					@uploadPercent="uploadPercent" :percent="item.percent?item.percent:0"
					:class="item.mediaType=='video'?'videoView':'uploadBtn'"></UploadView>

			</view>
			<view class="footer">

				<view class="upload-img" @click="insertImage">
					<image class="" src="https://dnsverify.pfmoto.com/appstatic/community/upload-img.png" mode="">
					</image>
					<text>添加问题图片</text>
				</view>

				<!-- #ifdef MP-WEIXIN -->
				<view v-if="content==''||title == ''||checkboxValue.length==0 ||content.length<=0" class="commentTouched_" @click="commentTouched">
					+发布
				</view>
				<view v-else class="commentTouched" @click="commentTouched">+发布</view>
				<!-- #endif -->
			</view>
			
		</view>
	</view>
</template>
<script>
	const app = getApp();
	const util = require('@/utils/util.js');
	const network = require('@/manager/network-manager.js');
	const dialog = require('@/utils/dialog.js');
	import UploadView from '@/components/UploadView/UploadView.vue'
	import wCache from '@/utils/wCache.js'
	import titlebara from '@/components/titlebar/titlebar'
	export default {
		components: {
			UploadView,
			titlebara
		},
		data() {
			return {
				top: app.globalData.statusBarHeight + 44,
				formats: {},
				show: false,
				selector: ['拍摄', '从手机相册选择'],
				showPicker: false,
				content: '',
				title: '',
				done:'done',
				fileList: [{
					type: 0,
					mediaType: 'add',
					url: '',
					path: '',
					uuid: util.createUidKey()
				}],


				imgList: [],


				showUpload: false,

				checkboxValue: [],

				checkboxList: [
					{
						name: '车辆',
						disabled: false,
						dictionaryId: ''
					},
					{
						name: '售后',
						disabled: false,
						dictionaryId: ''
					},
					{
						name: '其他',
						disabled: false,
						dictionaryId: ''
					},
					{
						name: '车联网',
						disabled: false,
						dictionaryId: ''
					},
					{
						name: 'APP使用',
						disabled: false,
						dictionaryId: ''
					},
					{
						name: '试驾与交付',
						disabled: false,
						dictionaryId: ''
					}
				],
				showUploadImg: false,
				disabled: false,
				flag: false,
				urls: [],
				dictIds:[0],
				contentCode:'1',
				cover:'',
				lastCheckValue:[]
			};
		},
		onLoad(data) {
			
		},
		onShow() {

		},
		created() {
			this.loadQuwstionType()
			// this.loadAskType()
		},
		methods: {
			checkboxChange(val) {
				var that = this
				
				// if(val.indexOf(0) == -1&&this.lastCheckValue.indexOf(0) >-1){
				// 	that.$nextTick(function(){
				// 		that.checkboxValue = []
				// 	})
				// }else if(val.indexOf(0)>-1){
					
					// that.$nextTick(function(){
					// 	that.checkboxValue = this.dictIds
					// })
					
				// }
				that.checkboxValue = val
				this.lastCheckValue = val
			},
			loadQuwstionType() {
				var that = this;
				var uri = app.globalData.config.interfaces.URL_DICTIONARY_GETDICTIONARYLIST;
				var params = {
					dictionaryCode: 'PF_ASK_TYPE'
				};
				network.get(uri, params, 'json').then(res => {
					if (res.code == 200) {
						that.dictIds = [0]
						res.data.map(v => {
							that.checkboxList.map(item => {
								if (v.contentName == item.name) {
									
									item.dictionaryId = v.uuid
									
								}
							})
							that.dictIds.push(v.uuid)
						})
					} else {
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {
				
					uni.showToast({
						title: res.errMsg,
						duration: 3000,
						icon: 'none'
					})
				});

			},
			loadAskType() {
			
				var that = this;
				var uri = app.globalData.config.interfaces.URL_DICTIONARY_GETDICTIONARYLIST;
				
				var param = {
					dictionaryCode: 'LEVC_USER_PUBLISH_TYPE'
				};
				network.get(uri, param, 'json').then(res => {
				
					if (res.code == 200) {
						that.dictIds = [0]
						res.data.map(v => {
							if(item.contentName == '用户')
							that.contentCode = item.contentCode
						})
					} else {
						
						uni.showToast({
							title: res.message,
							duration: 3000,
							icon: 'none'
						})
					}
				}).catch(res => {
					
					uni.showToast({
						title: res.errMsg,
						duration: 3000,
						icon: 'none'
					})
				});
			
			},
			changeData(val) {
				this.content = val.detail.html
			},

			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},

			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success")
					}
				})
			},

			uploadFile(fileUrl, mediaType) {
				var _self = this;
				var uploadUrl = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_ALIYUN_OSS_UPLOAD
				var uploadTask = uni.uploadFile({
					url: uploadUrl, //仅为示例，非真实的接口地址
					filePath: fileUrl,
					name: 'file',
					header: {
						"token": "Bearer " + app.globalData.token,
						"Authorization": "Bearer " + app.globalData.token,
					},
					success: (uploadFileRes) => {
						var uploadFileData = JSON.parse(uploadFileRes.data);
						if (uploadFileData.code == 200) {
							this.editorCtx.insertImage({
								src: uploadFileData.data,
								alt: '图像',
								success: function() {
									console.log(_self.fileList)
									_self.urls.push(uploadFileData.data)
								}
							})
						} else {
							setTimeout(() => {
								uni.showToast({
									title: "上传失败" + uploadFileData.message,
									duration: 3000,
									icon: 'none'
								})
							}, 500);


						}
					},
					fail(e) {
						console.log("上传失败", e);
					}
				});

			},

			insertImage() {
				uni.chooseImage({
					count: 9,
					// success: (res) => {
					// 	console.log(res)
					// 	this.uploadFile(res.tempFilePaths[0], 'image')

					// }
					success: (res) => {
						console.log('res!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'+ JSON.stringify(res))
						for(var i=0;i<res.tempFilePaths.length;i++){
							this.uploadFile(res.tempFilePaths[i], 'image')
						}
					}
				})
			},
			closePopup() {
				this.show = false
				this.selectTopic = []
				console.log(this.oldSelectTopic)
				this.topicList.map(item => {
					item.select = false
				})
			},
			confirmTopic() {

				this.show = false
				// this.oldSelectTopic = this.selectTopic
			},

			selectMedia() {
				var that = this
				uni.showActionSheet({
					itemList: that.selector,
					success: function(res) {
						that.confirm(res.tapIndex + 1)
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			custom() {
				this.topic = ""
			},
			confirm(e) {

				if (this.fileList.length == 20) {
					uni.showToast({
						title: '最多20张图',
						duration: 3000,
						icon: 'none'
					})
					return
				}
				console.log(this.fileList[0].mediaType)
				var index = this.fileList.length - 1;
				this.$refs['uploadView' + index][0].upload(e)

			},
			imgMatch(str){
			  var data = '';
			   str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/, function (match, capture) {
			     data = capture;
			   });
			  return data
			 },
			commentTouched() {
				if (this.flag) {
					return
				}
				var that = this;
				var uri = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_ACTIVITY_ADDQUESTION;
				this.imgList = []
				if (this.title == '') {
					uni.showToast({
						title: '请输入问答标题',
						duration: 3000,
						icon: 'none'
					})
					return
				}
				if(this.checkboxValue.length == 0){
					uni.showToast({
						title: '请选择问题类型',
						duration: 3000,
						icon: 'none'
					})
					return
				}
				for (let i in this.fileList) {
					if (this.fileList[i].url) {
						this.imgList.push(this.fileList[i].url)
					}
				}
				var askType = JSON.parse(JSON.stringify(this.checkboxValue))
				
				if(askType.indexOf(0)>-1){
					askType.splice(askType.indexOf(0),1)
				}
				if (this.content.match(/<img/g) && this.content.match(/<img/g).length > 20) {
					uni.showToast({
						title: '问答正文最多20张图片',
						duration: 3000,
						icon: 'none'
					})
					return
				}

				var contentLen = this.content.replace(/<\/?.+?\/?>/g, '')

				if (contentLen.length <= 0 && this.urls.length <= 0) {
					uni.showToast({
						title: '请输入问答内容',
						duration: 3000,
						icon: 'none'
					})
					return
				} else if (contentLen.length >= 10000) {
					uni.showToast({
						title: '问答内容不能超过10000字符',
						duration: 3000,
						icon: 'none'
					})
					return
				}
				var params = {
					authorId: app.getUserId(),
					title: this.title,
					apppublishFlag: 1,
					isfrom: 4,
					urls: this.urls,
					askType:askType.join(','),
					content: this.content,
					authorType:this.contentCode||	'1'
				}
				this.flag = true
				this.disabled = true
				network.post(uri, params, 'json').then(res => {
					if (res.code == 200) {
						that.clearData()
						uni.showToast({
							title: '发布成功',
							duration: 3000
						})

						app.globalData.workSwiper = 2
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/community/community'
							});
						}, 500);
					} else {
						setTimeout(() => {
							uni.showToast({
								title: res.message,
								duration: 3000,
								icon: 'none'
							})
						}, 500);
						this.disabled = false
					}
					that.flag = false
				}).catch(res => {
					that.flag = false
					setTimeout(() => {
						uni.showToast({
							title: res.errMsg,
							duration: 3000,
							icon: 'none'
						})
					}, 500);
					console.error(res);
					this.disabled = false
				});
			},
			toSelectTopic() {
				this.show = true
			},
			delImg(index) {
				console.log(index);
				this.fileList.splice(index, 1);
				console.log(this.fileList);
			},
			swichType(type) {

				if (type === 0) {
					this.showUpload = true;
				} else {
					this.showTopic = true;
				}
			},
			clearData() {
				this.fileList = [{
					type: 0,
					mediaType: 'add',
					url: '',
					path: '',
					uuid: util.createUidKey()
				}]
				this.content = ''
				this.title = ''
				this.clear()
			},
			uploadPercent(item) {
				// console.log(12312312)
				// console.log(item, 'uploadPercent')
				// for (let i in this.fileList) {
				// 	if (this.fileList[i].uuid == item.uuid) {
				// 		this.fileList[i].percent = item.percent
				// 	}
				// }
			},
			uploading(item) {
				//to do 上传视频只能上传一个限制
				if (item.mediaType == 'video') {
					return
				}
				console.log('巴拉巴拉')
				// this.fileList.push(item)
				this.fileList.push({
					type: 0,
					mediaType: 'add',
					url: '',
					path: '',
					uuid: util.createUidKey()
				})
			},
			uploadSuccess(item) {
				uni.hideLoading()
				this.cover = item.url
				// this.fileList.findIndex(x => x.uuid === item.uuid).url = item.url;
			},
			uploadError(item) {
				console.log(item);
				this.fileList.splice(this.fileList.findIndex(x => x.uuid === item.uuid), 1);
			},
			uploadDelete(item) {
				console.log(item);

				this.fileList.splice(this.fileList.findIndex(x => x.uuid === item.uuid), 1);
				if (item.mediaType == 'video') {
					this.fileList.push({
						type: 0,
						mediaType: 'add',
						url: '',
						path: '',
						uuid: util.createUidKey()
					})
				}
				console.log(this.fileList);
			},
		},
	};
</script>

<style lang="scss">
	@import "./editor-icon.css";

	page {
		width: 100%;
		height: 100%;
		background: #f5f5f5;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		text-align: center;
	}

	/deep/.u-checkbox-group {
		padding: 18rpx;
	}

	.question_type {
		font-size: 28rpx;
		line-height: 80rpx;
		/* identical to box height */
		padding: 18rpx;
		display: flex;
		align-items: center;

		/* 力帆-禁用 */

		color: #ADB0AE;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 24upx 20upx;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		margin-top: 20px;
		font-size: 16px;
		line-height: 1.5;
	}

	.titleText {
		color: #3D3A3A;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-weight: 600;
		font-size: 16px;
		align-items: center;
		display: flex;
		position: absolute;
		top: calc(50% - 10px);
		left: calc((100% - 40px)/2);
	}

	.titleCommentTouched {
		width: 60px;
		height: 30px;
		box-sizing: border-box;
		border-radius: 2px;
		text-align: center;
		line-height: 30px;
		align-items: center;
		font-size: 14px;
		color: #FFFFFF;
		border: 1px solid #EA5404;
		background-color: #EA5404;
		position: absolute;
		left: calc(100% - 84px - 16px);
		top: calc(50% - 16px);
	}

	.titleCommentTouched_ {
		width: 60px;
		height: 30px;
		box-sizing: border-box;
		border-radius: 2px;
		text-align: center;
		line-height: 30px;
		align-items: center;
		font-size: 14px;
		color: #ADB0AE;
		border: 1px solid #EDEDED;
		background-color: #EDEDED;
		position: absolute;
		left: calc(100% - 84px - 16px);
		top: calc(50% - 16px);
	}

	.showMore {
		width: 60px;
		height: 30px;
		position: absolute;
		top: calc(50% - 15px);
		left: calc(100% - 70px);
	}

	.content-pd {
		padding-bottom: 120upx;
	}

	.releaseState {
		width: calc(100vw - 60rpx);
		height: 100%;
		background: url("https://dnsverify.pfmoto.com/appstatic/my/my_icon_list_background.jpg") no-repeat;
		background-size: 100%, 100vh;
		position: absolute;
		/*#ifdef MP-WEIXIN*/
		top: 88px;
		/*#endif*/
		/*#ifdef APP-PLUS||H5*/
		top: 44px;
		/*#endif*/
	}

	.popup {
		padding: 30rpx;
	}

	/deep/.ql-blank:before {
		font-style: normal !important;
		font-size: 28rpx;
		color: #ADB0AE;
		font-weight: 400;
	}

	.action-wraper {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 20rpx;
	}

	#editor {
		width: 100%;
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 400;
		font-size: 14px;
		line-height: 20px;
		text-transform: uppercase;
		color: #333333;
		margin-top: 15px;

	}

	.action-wraper text {
		font-size: 32rpx;
		font-weight: 600;
		color: #3d3a3a;
	}

	/deep/ .u-textarea__count {
		position: relative;
		top: 0;
	}

	/deep/ .u-textarea,
	/deep/ .u-textarea__count {
		background-color: transparent !important;
	}

	.action-wraper image {
		width: 48rpx;
		height: 48rpx;
	}

	/deep/ u-search {
		margin-bottom: 30rpx;
	}

	.noData {
		margin-top: 40rpx;
		display: flex;
		justify-content: space-between;
	}

	.noData text {
		font-size: 28rpx;
	}

	.noData text:first-child {
		color: #ADB0AE;
	}

	.noData text:last-child {
		color: #ea5454;
	}





	/deep/.u-checkbox-group--row {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}

	/deep/.u-checkbox {
		margin: 10rpx 0;
		width: 200rpx;
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}

	/deep/.u-checkbox span {
		font-size: 28rpx;
	}

	.u-checkbox:nth-child(7) {
		width: 200rpx;
	}

	.upload-img image {
		width: 40rpx;
		height: 36rpx;
		margin-right: 8rpx;
		position: relative;
		top: 6rpx;

	}

	.upload-img text {
		font-size: 28rpx;

		color: #3D3A3A;
	}

	.topic .close-topic {
		width: 32rpx;
		height: 32rpx;
		position: relative;
		top: 0;
		right: -14rpx;
	}

	.topic image {
		width: 24rpx;
		height: 24rpx;
	}

	.topic-item text {
		color: #EA5404;
		padding-left: 20rpx;
	}

	.topic image {
		width: 24rpx;
		height: 24rpx;
	}

	.inputGreybg,
	.inputGreybg .uploadImg {
		width: 100%;
		height: 396rpx;
		display: inline-block;
	}

	.topicWraper {
		font-size: 28rpx;
		color: #828282;
		display: flex;

		padding: 40rpx 0;
		margin-top: 20rpx;
	}

	.releaseState {
		padding: 0 30rpx;

		.textarea {
			font-size: 28rpx;
			line-height: 160%;
			color: #bdbdbd;
			width: 100%;
			padding-top: 30rpx;
		}

		.uploadImg {
			margin-top: 20rpx;

			.videoClass {
				width: 100%;

				#myVideo {
					width: 100%;
				}
			}

			.imageList {
				margin: 6rpx 6rpx 0 0;
				display: inline-block;
				position: relative;

				.image {
					width: 216rpx;
					height: 216rpx;
					display: inline-block;
					border-radius: 20rpx;
				}

				.delImg {
					position: absolute;
					right: 8rpx;
					top: 8rpx;
					width: 40rpx;
					height: 40rpx;
					z-index: 2;
				}
			}

			.onlyImageList {
				.onlyImage {
					width: 100%;
					display: inline-block;
				}
			}
		}

		.uploadBtn {
			width: 216rpx;
			height: 216rpx;
			border-radius: 20rpx;
			display: inline-block;
		}

		.videoView {
			width: 672rpx;
			height: 522rpx;
			border-radius: 20rpx;
			display: inline-block;
			margin-bottom: 100rpx;
		}

		.uploadTopic {

			font-weight: bold;
			font-size: 28rpx;
			line-height: 40rpx;
			color: #bdbdbd;
			display: flex;
			align-items: center;

			.topicName {

				display: inline-block;

				width: 164rpx;
				height: 48rpx;
				line-height: 48rpx;
				font-size: 28rpx;
				color: #3d3a3a;
				left: 0px;
				top: 0px;
				text-align: center;
				background: rgba(61, 58, 58, 0.1);
				border-radius: 4rpx;

				.s-topic {
					width: 30rpx;
					height: 30rpx;
					position: relative;
					left: -10rpx;
					top: 4rpx;
				}
			}

			.deltopic {
				width: 40rpx;
				height: 40rpx;
				margin-left: 6rpx;
				position: relative;
				top: 10rpx;
			}
		}

		.footer {
			position: fixed;
			bottom: 0rpx;
			left: 0;
			right: 0;
			display: flex;
			flex-direction: row;
			align-items: center;
			background-color: #f5f5f5;
			padding: 30rpx 46rpx;
		}

		.commentTouched {
			width: 84px;
			height: 32px;
			box-sizing: border-box;
			border-radius: 2px;
			text-align: center;
			line-height: 32px;
			align-items: center;
			font-size: 14px;
			color: #FFFFFF;
			border: 1px solid #EA5404;
			background-color: #EA5404;
			position: absolute;
			left: calc(100% - 84px - 16px);
			top: calc(50% - 16px);
		}

		.commentTouched_ {
			width: 84px;
			height: 32px;
			box-sizing: border-box;
			border-radius: 2px;
			text-align: center;
			line-height: 32px;
			align-items: center;
			font-size: 14px;
			color: #ADB0AE;
			border: 1px solid #EDEDED;
			background-color: #EDEDED;
			position: absolute;
			left: calc(100% - 84px - 16px);
			top: calc(50% - 16px);
		}
	}
	
</style>
